//
//  CityViewController.m
//  SXH
//
//  Created by 房 国生 on 15/8/3.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "CityViewController.h"
#import "LocationManagement.h"
#import "LocationTableViewCell.h"
#import "HotCityTableViewCell.h"
#import "CommonService.h"
#import "AppDelegate.h"
#import "DBCityHistoryManager.h"
#import "CityModel.h"
#import "NSString+PinYin.h"

#import "LPUtils.h"

@interface CityViewController () <LocationManagementDelegate, CitySelDelegate> {
    BOOL showSearch;
}

@property (nonatomic, strong) IBOutlet UILabel *labelBg;
@property (nonatomic, strong) IBOutlet UITextField *textFieldKey;

@end


#define K_title  @"选择城市"

#define K_currentString  @"当前"
#define K_currentCellIdentifier  @"LocationTableViewCell"

#define K_historyString  @"历史"
#define K_historyCellIdentifier  @"HotCityTableViewCell"

#define K_hotString      @"热门"

#define K_locationFail   @"定位失败，请点击重试"

@implementation CityViewController

@synthesize labelBg, textFieldKey;

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.arrayHotCity = [NSMutableArray array];
        self.keys = [NSMutableArray array];
        self.arrayCitys = [NSMutableArray array];
    }
    return self;
}

- (void)getCityDataNew {
    CommonService *service = [[CommonService alloc] init];
    [service getNetWorkData:nil
                       Path:City_date
                  Successed:^(id entity) {
                      NSMutableArray *arr = [CityModel arrayOfModelsFromDictionaries:[entity objectForKey:@"rows"] error:nil];
                      [self dealSectionArrWithArr:arr];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}


/**
 处理头部数据源
 */
- (void)dealSectionArrWithArr:(NSMutableArray *)arr {
    for (int i = 0; i < arr.count; i ++) {
        CityModel *tmpModel = arr[i];
        NSString *keyStr = [tmpModel.cname getFirstLetter];
        
        if (![self.sectionDic.allKeys containsObject:keyStr]) {
            NSMutableArray *tmpArr = [[NSMutableArray alloc]init];
            [self.sectionDic setObject:tmpArr forKey:keyStr];
        }
        NSMutableArray *valueArr = [self.sectionDic objectForKey:keyStr];
        [valueArr addObject:tmpModel];
    }
    self.keySortedArr = [self.sectionDic.allKeys mutableCopy];
    for (int i = 0; i < self.keySortedArr.count; i ++) {
        for (int j = i + 1; j < self.keySortedArr.count; j ++) {
            NSString *strI = self.keySortedArr[i];
            NSString *strJ = self.keySortedArr[j];
            char a = [strI characterAtIndex:0];
            char b = [strJ characterAtIndex:0];
            if (a > b) {
                [self.keySortedArr exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
    for (int i = 0; i < self.keySortedArr.count; i ++) {
        NSMutableArray *tmpArr = [self.sectionDic objectForKey:self.keySortedArr[i]];
        [self.cityArr addObject:tmpArr];
    }
    [self.tableViewCity reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = K_title;
    [self getCityDataNew];
    
    [labelBg.layer setMasksToBounds:YES];
    [labelBg.layer setCornerRadius:6.0]; //设置矩形四个圆角半径
    
    [self getCityData];
    
    NSMutableArray *arrayRes = [DBCityHistoryManager selectAllSearchRes];
    [[AppDelegate instance].cities setObject:arrayRes forKey:K_historyString];
    
    // Do any additional setup after loading the view.
    CGRect frame = CGRectMake(0, labelBg.frame.origin.y + labelBg.frame.size.height + 10, self.view.frame.size.width, self.view.frame.size.height - labelBg.frame.size.height - 75);
    _tableViewCity = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    _tableViewCity.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
    _tableViewCity.backgroundColor = [UIColor clearColor];
    _tableViewCity.delegate = self;
    _tableViewCity.dataSource = self;
    _tableViewCity.sectionIndexBackgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.97 alpha:1];
    _tableViewCity.sectionIndexColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
    [self.view addSubview:_tableViewCity];
    
    [self getHotSearch];
    textFieldKey.delegate = self;
    
    _dicSearchCities = [[NSMutableDictionary alloc] init];
    showSearch = NO;
}

#pragma mark - 获取城市数据
- (void) getCityData
{
    [self.keys addObjectsFromArray:[[[AppDelegate instance].cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    //添加热门城市
    NSString *strHot = K_hotString;
    [self.keys insertObject:strHot atIndex:0];
    //[self.cities setObject:_arrayHotCity forKey:strHot];
    
    NSString *strHistory = K_historyString;
    [self.keys insertObject:strHistory atIndex:0];
    
    NSString *strLocation = K_currentString;
    [self.keys insertObject:strLocation atIndex:0];
    [self updateLocationHeader];
}

#pragma mark - tableView
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    NSMutableArray *tmpArr = [self.keySortedArr mutableCopy];
    [tmpArr insertObject:K_hotString atIndex:0];
    [tmpArr insertObject:K_historyString atIndex:0];
    [tmpArr insertObject:K_currentString atIndex:0];
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    bgView.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.95 alpha:1];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 30)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor darkGrayColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    
    NSString *key = [_keys objectAtIndex:section];
    if ([key rangeOfString:K_hotString].location != NSNotFound) {
        titleLabel.text = @"热门城市";
    }
    else {
        titleLabel.text = key;
        titleLabel.text = tmpArr[section];
    }
    if (showSearch) {
        titleLabel.text = self.searchSortedArr[section];
    }
    
    [bgView addSubview:titleLabel];
    
    return bgView;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *tmpArr = [self.keySortedArr mutableCopy];
    [tmpArr insertObject:K_hotString atIndex:0];
    [tmpArr insertObject:K_historyString atIndex:0];
    [tmpArr insertObject:K_currentString atIndex:0];
    return tmpArr;
//    return _keys;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
//    return [_keys count];
    if (showSearch) {
        return _searchDic.allKeys.count;
    }
    return self.cityArr.count + 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (showSearch == YES) {
        NSString *tmpStr = self.searchSortedArr[section];
        NSMutableArray *tmpArr = [self.searchDic objectForKey:tmpStr];
        return tmpArr.count;
    }
    
    // Return the number of rows in the section.
    NSString *key = [_keys objectAtIndex:section];
    NSArray *citySection = nil;
    
    if (showSearch == NO) {
        citySection = [[AppDelegate instance].cities objectForKey:key];
    } else {
        citySection = [_dicSearchCities objectForKey:key];
    }
    if (section > 2) {
        NSMutableArray *tmpArr = self.cityArr[section - 3];
        return tmpArr.count;;
    }
    if (section == 2) {
        return [_hotCityArr count]/3 + ([_hotCityArr count]%3 > 0 ?1:0);
    }
    
    if ([key isEqualToString:K_hotString] == YES || [key isEqualToString:K_historyString] == YES) {
        DebugLog(@"%lu", [citySection count]/3 + ([citySection count]%3 >0 ?1:0));
        return [citySection count]/3 + ([citySection count]%3 > 0 ?1:0);
    } else {
        return [citySection count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (showSearch) {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor whiteColor];
            //cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.textLabel setTextColor:[UIColor blackColor]];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        }
        
        //        NSDictionary *dic = nil;
        //        if (showSearch == NO) {
        //            dic = [[[AppDelegate instance].cities objectForKey:key] objectAtIndex:indexPath.row];
        //        } else {
        //            dic = [[_dicSearchCities objectForKey:key] objectAtIndex:indexPath.row];
        //        }
        NSString *key = self.searchSortedArr[indexPath.section];
        NSMutableArray *tmpArr = [self.searchDic objectForKey:key];
        CityModel *model = tmpArr[indexPath.row];
        //        cell.textLabel.text = [dic objectForKey:@"cname"];
        cell.textLabel.text = model.cname;
        return cell;
    }
    NSString *key = [_keys objectAtIndex:indexPath.section];
    if ([key isEqualToString:K_currentString] == YES) {
        static NSString *couponTableViewCellIdentifier=K_currentCellIdentifier;
        LocationTableViewCell *cell = (LocationTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_currentCellIdentifier owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        NSDictionary *dic = nil;
        if (showSearch == NO) {
            dic = [[[AppDelegate instance].cities objectForKey:key] objectAtIndex:indexPath.row];
        } else {
            dic = [[_dicSearchCities objectForKey:key] objectAtIndex:indexPath.row];
        }
        
        cell.labelGPS.text = @"GPS定位";
        
        if ([[dic objectForKey:@"cname"] isEqualToString:K_locationFail] == YES) {
            cell.labelGPS.hidden = YES;
        } else {
            cell.labelGPS.hidden = NO;
        }
        cell.labelLocation.text = [dic objectForKey:@"cname"];
        
        return cell;
    }
    else if ([key isEqualToString:K_historyString] == YES) {
        static NSString *couponTableViewCellIdentifier=K_historyCellIdentifier;
        HotCityTableViewCell *cell = (HotCityTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_historyCellIdentifier owner:self options:nil];
            cell = [array objectAtIndex:0];
            cell.delegate = self;
        }
        
        NSArray *hotSearchSection = nil;
        if (showSearch == NO) {
            hotSearchSection = [[AppDelegate instance].cities objectForKey:key];
        } else {
            hotSearchSection = [_dicSearchCities objectForKey:key];
        }
        
        //
        if (indexPath.row*3 < [hotSearchSection count]) {
            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3];
            
            [cell.btnLeft setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
            cell.btnLeft.tag = [[dic valueForKey:@"id"] integerValue];
            cell.btnLeft.hidden = NO;
            [LPUtils setButtonStyle:cell.btnLeft];
        }
        
        if (indexPath.row*3 + 1 < [hotSearchSection count]) {
            
            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3 + 1];
            
            [cell.btnMiddle setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
            cell.btnMiddle.tag = [[dic valueForKey:@"id"] integerValue];
            cell.btnMiddle.hidden = NO;
            [LPUtils setButtonStyle:cell.btnMiddle];
        }
        
        if (indexPath.row*3 + 2 < [hotSearchSection count]) {
            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3 + 2];
            
            [cell.btnRight setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
            cell.btnRight.tag = [[dic valueForKey:@"id"] integerValue];
            cell.btnRight.hidden = NO;
            [LPUtils setButtonStyle:cell.btnRight];
        }
        cell.selectionStyle = NO;
       
        return cell;
    }
    else if ([key isEqualToString:K_hotString] == YES) {
        static NSString *couponTableViewCellIdentifier=K_historyCellIdentifier;
        HotCityTableViewCell *cell = (HotCityTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_historyCellIdentifier owner:self options:nil];
            cell = [array objectAtIndex:0];
            cell.delegate = self;
        }
        
        NSArray *hotSearchSection = nil;
        if (showSearch == NO) {
            hotSearchSection = [[AppDelegate instance].cities objectForKey:key];
        } else {
            hotSearchSection = [_dicSearchCities objectForKey:key];
        }

        if (indexPath.row*3 < [_hotCityArr count]) {
//            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3];
//            [cell.btnLeft setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
//            cell.btnLeft.tag = [[dic valueForKey:@"id"] integerValue];
            CityModel *model = self.hotCityArr[indexPath.row * 3];
            [cell.btnLeft setTitle:model.cname forState:UIControlStateNormal];
            cell.btnLeft.tag = [model.id integerValue];
            cell.btnLeft.hidden = NO;
            [LPUtils setButtonStyle:cell.btnLeft];
        }
        
        if (indexPath.row*3 + 1 < [_hotCityArr count]) {
            
//            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3 + 1];
//            
//            [cell.btnMiddle setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
//            cell.btnMiddle.tag = [[dic valueForKey:@"id"] integerValue];
            CityModel *model = self.hotCityArr[indexPath.row * 3 + 1];
            [cell.btnMiddle setTitle:model.cname forState:UIControlStateNormal];
            cell.btnMiddle.tag = [model.id integerValue];
            cell.btnMiddle.hidden = NO;
            [LPUtils setButtonStyle:cell.btnMiddle];
        }
        
        if (indexPath.row*3 + 2 < [_hotCityArr count]) {
//            NSDictionary *dic = [hotSearchSection objectAtIndex:indexPath.row*3 + 2];
//            
//            [cell.btnRight setTitle:[dic valueForKey:@"cname"] forState:UIControlStateNormal];
//            cell.btnRight.tag = [[dic valueForKey:@"id"] integerValue];
            CityModel *model = self.hotCityArr[indexPath.row * 3 + 2];
            [cell.btnRight setTitle:model.cname forState:UIControlStateNormal];
            cell.btnRight.tag = [model.id integerValue];
            cell.btnRight.hidden = NO;
            [LPUtils setButtonStyle:cell.btnRight];
        }

        cell.selectionStyle = NO;
        return cell;
    }
    else {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor whiteColor];
            //cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.textLabel setTextColor:[UIColor blackColor]];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
        }
        
//        NSDictionary *dic = nil;
//        if (showSearch == NO) {
//            dic = [[[AppDelegate instance].cities objectForKey:key] objectAtIndex:indexPath.row];
//        } else {
//            dic = [[_dicSearchCities objectForKey:key] objectAtIndex:indexPath.row];
//        }
        NSMutableArray *tmpArr = self.cityArr[indexPath.section - 3];
        CityModel *model = tmpArr[indexPath.row];
//        cell.textLabel.text = [dic objectForKey:@"cname"];
        cell.textLabel.text = model.cname;
        return cell;
    }
}

#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        NSArray *arrayLocation = [[AppDelegate instance].cities objectForKey:K_currentString];
        NSDictionary *dic = [arrayLocation firstObject];
        if ([[dic objectForKey:@"cname"] isEqualToString:K_locationFail] == YES) {
            [[LocationManagement sharedInstance] startUpdatingLocation];
            [dic setValue:@"cname" forKey:@"定位中..."];
        }
        else {
            [_delegate citySelAction:dic];
            [DBCityHistoryManager createTable];
            [DBCityHistoryManager saveOrUpdataEntity:dic];
            [self.navigationController popViewControllerAnimated:YES];
        }
        return;
    }
    
    NSString *key = [_keys objectAtIndex:indexPath.section];
    NSDictionary *dic = nil;
    CityModel *model;
    if (showSearch == NO) {
        dic = [[[AppDelegate instance].cities objectForKey:key] objectAtIndex:indexPath.row];
        NSMutableArray *tmpArr = self.cityArr[indexPath.section - 3];
        model = tmpArr[indexPath.row];
        dic = [model toDictionary];
        
    }
    else {
//        dic = [[_dicSearchCities objectForKey:key] objectAtIndex:indexPath.row];
        NSString *tmpKey = _searchSortedArr[indexPath.section];
        NSMutableArray *tmpArr = [self.searchDic objectForKey:tmpKey];
        model = tmpArr[indexPath.row];
        dic = [model toDictionary];
    }
    
    if ([key isEqualToString:K_currentString] == YES) {
        if ([[dic objectForKey:@"cname"] isEqualToString:K_locationFail] == YES) {
            [[LocationManagement sharedInstance] startUpdatingLocation];
            [dic setValue:@"cname" forKey:@"定位中..."];
        }
        else {
            [_delegate citySelAction:dic];
            [DBCityHistoryManager createTable];
            [DBCityHistoryManager saveOrUpdataEntity:dic];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    else if ([key isEqualToString:K_hotString] == YES){
//        [_delegate citySelAction:dic];
//        [self.navigationController popViewControllerAnimated:YES];
    }
    else if ([key isEqualToString:K_historyString] == YES){
        
    }
    else {
        [_delegate citySelAction:dic];
        [DBCityHistoryManager createTable];
        [DBCityHistoryManager saveOrUpdataEntity:dic];
        [self.navigationController popViewControllerAnimated:YES];
       
    }
    
    //
   
    
    DebugLog(@"%@, %@", [dic objectForKey:@"id"], [dic objectForKey:@"cname"]);
}

- (void)cityButtonAction:(NSInteger)tag {
    
    for (int i = 0; i < [self.keys count]; i++) {
        id key = [self.keys objectAtIndex: i];
        NSArray *citySection = nil;
        if (showSearch == NO) {
            citySection = [[AppDelegate instance].cities objectForKey:key];
        } else {
            citySection = [_dicSearchCities objectForKey:key];
        }
        
        for (int j = 0; j < [citySection count]; j++) {
            NSDictionary *city = [citySection objectAtIndex:j];
            if ([[city objectForKey:@"id"] integerValue] == tag) {
                [_delegate citySelAction:city];
                
                [DBCityHistoryManager createTable];
                [DBCityHistoryManager saveOrUpdataEntity:city];
                
                [AppDelegate instance].dicCurrentCity = city;
                [self.navigationController popViewControllerAnimated:YES];
                return;
            }
        }
    }
}

- (NSMutableDictionary *)sectionDic {
    if (!_sectionDic) {
        _sectionDic = [[NSMutableDictionary alloc]init];
    }
    return _sectionDic;
}

- (NSMutableArray *)cityArr {
    if (!_cityArr) {
        _cityArr = [[NSMutableArray alloc]init];
    }
    return _cityArr;
}

- (NSMutableArray *)keySortedArr {
    if (!_keySortedArr) {
        _keySortedArr = [[NSMutableArray alloc]init];
    }
    return _keySortedArr;
}

- (NSMutableArray *)hotCityArr {
    if (!_hotCityArr) {
        _hotCityArr = [[NSMutableArray alloc]init];
    }
    return _hotCityArr;
}

- (NSMutableArray *)historyArr {
    if (!_historyArr) {
        _historyArr = [[NSMutableArray alloc]init];
    }
    return _historyArr;
}

- (NSMutableDictionary *)searchDic {
    if (!_searchDic) {
        _searchDic = [[NSMutableDictionary alloc]init];
    }
    return _searchDic;
}

- (NSMutableArray *)searchSortedArr {
    if (!_searchSortedArr) {
        _searchSortedArr = [[NSMutableArray alloc]init];
    }
    return _searchSortedArr;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)locationUpdated {
    [self updateLocationHeader];
}

- (void)locationUpdatedFailed:(int)errorCode ErrorMessage:(NSString *)message {
    [self updateLocationHeader];
}

- (void)updateLocationHeader {
    
    [[AppDelegate instance].cities removeObjectForKey:K_currentString];
    
    [LocationManagement sharedInstance].city = [[LocationManagement sharedInstance].city stringByReplacingOccurrencesOfString:@"市" withString:@""];
    DebugLog(@"%@", [LocationManagement sharedInstance].city);
    if ([LocationManagement sharedInstance].city == nil) {
        [[LocationManagement sharedInstance] startUpdatingLocation];
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"", @"ID",K_locationFail, @"name",nil];
        NSMutableArray *arrayLocation = [NSMutableArray arrayWithObjects:dic, nil];
        [[AppDelegate instance].cities setObject:arrayLocation forKey:K_currentString];
        
    } else {
        NSMutableArray *arrayLocation = [[NSMutableArray alloc] init];
        for (int i = 0; i < [self.keys count]; i++) {
            id key = [self.keys objectAtIndex: i];
            NSArray *citySection = [[AppDelegate instance].cities objectForKey:key];
            
            for (int j = 0; j < [citySection count]; j++) {
                NSDictionary *city = [citySection objectAtIndex:j];
                if ([[LocationManagement sharedInstance].city isEqualToString:[city objectForKey:@"cname"]] == YES) {
                    [arrayLocation addObject:city];
                    [[AppDelegate instance].cities setObject:arrayLocation forKey:K_currentString];
                    return;
                }
            }
        }
    }
}

- (void) getHotSearch {
    CommonService *service = [[CommonService alloc] init];
    
    [service getNetWorkData:nil
                       Path:HOT_CITY
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
//                      NSArray *array = [dic objectForKey:@"rows"];
//                      //NSMutableArray *mutalbeArray = [[NSMutableArray alloc] init];
//                      for (int i = 0; i < [array count]; i++) {
//                          NSDictionary *obj = [array objectAtIndex:i];
//                          NSNumber *cid = [obj valueForKeyPath:@"id"];
//                          NSString *strId = [NSString stringWithFormat:@"%d", [cid intValue]];
//                          NSString *cname = [obj valueForKeyPath:@"cname"];
//                          
//                          NSDictionary *dicCity = [[NSDictionary alloc] initWithObjectsAndKeys:strId, @"id",cname, @"cname", nil];
//                          [self.arrayHotCity addObject:dicCity];
//                      }
//                      [[AppDelegate instance].cities setObject:self.arrayHotCity forKey:@"热门"];
                      self.hotCityArr = [CityModel arrayOfModelsFromDictionaries:[dic objectForKey:@"rows"] error:nil];
                      
                      [_tableViewCity reloadData];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.textFieldKey) {
        [textFieldKey resignFirstResponder];
        [self searchCity:textFieldKey.text];
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    DebugLog(@"textFieldShouldClear");
    if (textField == self.textFieldKey) {
        [textFieldKey resignFirstResponder];
        showSearch  = NO;
        [self.keys removeAllObjects];
        [[AppDelegate instance].cities removeObjectForKey:K_currentString];
        [[AppDelegate instance].cities removeObjectForKey:K_historyString];
        [[AppDelegate instance].cities removeObjectForKey:K_hotString];
        [self getCityData];
        [_tableViewCity reloadData];
    }
    return YES;
}

- (void) searchCity:(NSString *)strKey {
    
    [_dicSearchCities removeAllObjects];
    [self.searchSortedArr removeAllObjects];
    [self.searchDic removeAllObjects];
    
//    NSMutableArray *tempKeys = [[NSMutableArray alloc] init];
//    showSearch = YES;
//    
//    for (int i = 0; i < [self.keys count]; i++) {
//        id key = [self.keys objectAtIndex: i];
//        NSArray *citySection = [[AppDelegate instance].cities objectForKey:key];
//        NSMutableArray *arraySearch = [[NSMutableArray alloc] init];
//        for (int j = 0; j < [citySection count]; j++) {
//            NSDictionary *city = [citySection objectAtIndex:j];
//            if ([[city objectForKey:@"cname"] containsString:strKey]) {
//                NSDictionary *citySearch = [[NSDictionary alloc] initWithDictionary:city] ;
//                [arraySearch addObject:citySearch];
//            }
//        }
//        
//        if ([arraySearch count] > 0) {
//            [tempKeys addObject:key];
//            [_dicSearchCities setObject:arraySearch forKey:key];
//        }
//    }
//    
//    [self.keys removeAllObjects];
//    
//    for (int i = 0; i < [tempKeys count]; i++) {
//        NSString *key = [tempKeys objectAtIndex:i];
//        [self.keys addObject:key];
//    }
    
    showSearch = YES;
    for (NSString *tmpKey in self.sectionDic.allKeys) {
        NSMutableArray *tmpArr = [self.sectionDic objectForKey:tmpKey];
        NSMutableArray *searchArr = [[NSMutableArray alloc]init];
        for (CityModel *tmpModel in tmpArr) {
            if ([tmpModel.cname containsString:strKey]) {
                [searchArr addObject:tmpModel];
            }
        }
        if (searchArr.count > 0) {
            [self.searchDic setObject:searchArr forKey:tmpKey];
        }
    }
    self.searchSortedArr = [self.searchDic.allKeys mutableCopy];
    for (int i = 0; i < self.searchSortedArr.count; i ++) {
        for (int j = i + 1; j < self.searchSortedArr.count; j ++) {
            NSString *strI = self.searchSortedArr[i];
            NSString *strJ = self.searchSortedArr[j];
            char a = [strI characterAtIndex:0];
            char b = [strJ characterAtIndex:0];
            if (a > b) {
                [self.searchSortedArr exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
    [_tableViewCity reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"CityViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"CityViewController"];
}

@end



